<template>
  <div class="audit-log-container">
    <div class="page-header">
      <h2>审计日志</h2>
      <p>查看系统操作记录和用户行为日志</p>
    </div>

    <!-- 搜索筛选区域 -->
    <div class="search-section">
      <el-card>
        <el-form :model="searchForm" :inline="true" class="search-form">
          <el-form-item label="操作类型">
            <el-select v-model="searchForm.actionType" placeholder="请选择操作类型" clearable style="width: 100px;">
              <el-option
                v-for="item in actionTypes"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="模块">
            <el-select v-model="searchForm.module" placeholder="请选择模块" clearable style="width: 100px;">
              <el-option
                v-for="item in modules"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="关键词">
            <el-input
              v-model="searchForm.keyword"
              placeholder="搜索描述、用户名、目标名称"
              clearable
            />
          </el-form-item>

          <el-form-item label="时间范围">
            <el-date-picker
              v-model="dateRange"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>

          <el-form-item label="操作结果">
            <el-select v-model="searchForm.result" placeholder="请选择操作结果" clearable style="width: 100px;">
              <el-option label="成功" value="成功" />
              <el-option label="失败" value="失败" />
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="handleSearch" :loading="loading">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="handleReset">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <!-- 日志列表 -->
    <div class="table-section">
      <el-card>
        <div class="table-header">
          <div class="table-title">
            <h3>日志列表</h3>
            <span class="total-count">共 {{ totalCount }} 条记录</span>
          </div>
          <el-button @click="handleRefresh" :loading="loading">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>

        <el-table
          :data="logList"
          v-loading="loading"
          stripe
          border
          style="width: 100%"
          :default-sort="{ prop: 'actionTime', order: 'descending' }"
        >
          <el-table-column prop="actionTime" label="操作时间" width="180" sortable>
            <template #default="{ row }">
              {{ formatDateTime(row.actionTime) }}
            </template>
          </el-table-column>

          <el-table-column prop="actionType" label="操作类型" width="100">
            <template #default="{ row }">
              <el-tag :type="getActionTypeTagType(row.actionType)">
                {{ row.actionType }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column prop="module" label="模块" width="100">
            <template #default="{ row }">
              <el-tag type="info">{{ row.module }}</el-tag>
            </template>
          </el-table-column>

          <el-table-column prop="description" label="操作描述" min-width="200" show-overflow-tooltip />

           <el-table-column prop="userName" label="操作者" width="120">
             <template #default="{ row }">
               <div>
                 <div>{{ row.userName }}</div>
                 <div class="user-real-name">{{ row.account }}</div>
               </div>
             </template>
           </el-table-column>

          <el-table-column prop="targetName" label="目标对象" width="150" show-overflow-tooltip />

          <el-table-column prop="result" label="结果" width="80">
            <template #default="{ row }">
              <el-tag :type="row.result === '成功' ? 'success' : 'danger'">
                {{ row.result }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column prop="clientIp" label="IP地址" width="120" />

          <el-table-column label="操作" width="120" fixed="right">
            <template #default="{ row }">
              <el-button
                type="primary"
                size="small"
                @click="handleViewDetail(row)"
              >
                详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="pagination.page"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="totalCount"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="日志详情"
      width="1000px"
      :close-on-click-modal="false"
    >
      <div v-if="currentLog" class="log-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="操作时间">
            {{ formatDateTime(currentLog.actionTime) }}
          </el-descriptions-item>
          <el-descriptions-item label="操作类型">
            <el-tag :type="getActionTypeTagType(currentLog.actionType)">
              {{ currentLog.actionType }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="模块">
            <el-tag type="info">{{ currentLog.module }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="操作结果">
            <el-tag :type="currentLog.result === '成功' ? 'success' : 'danger'">
              {{ currentLog.result }}
            </el-tag>
          </el-descriptions-item>
           <el-descriptions-item label="操作者">
             {{ currentLog.userName }} ({{ currentLog.account }})
           </el-descriptions-item>
          <el-descriptions-item label="目标对象">
            {{ currentLog.targetName || '无' }}
          </el-descriptions-item>
          <el-descriptions-item label="IP地址">
            {{ currentLog.clientIp || '无' }}
          </el-descriptions-item>
          <el-descriptions-item label="用户代理">
            {{ currentLog.userAgent || '无' }}
          </el-descriptions-item>
          <el-descriptions-item label="操作描述" :span="2">
            {{ currentLog.description }}
          </el-descriptions-item>
          <el-descriptions-item v-if="currentLog.errorMessage" label="错误信息" :span="2">
            <el-text type="danger">{{ currentLog.errorMessage }}</el-text>
          </el-descriptions-item>
        </el-descriptions>

        <!-- 数据变更详情 -->
        <div v-if="currentLog.oldValues || currentLog.newValues" class="data-changes">
          <h4>数据变更</h4>
          <el-row :gutter="20">
            <el-col :span="12" v-if="currentLog.oldValues">
              <h5>变更前</h5>
              <el-input
                type="textarea"
                :rows="6"
                :value="formatJson(currentLog.oldValues)"
                readonly
              />
            </el-col>
            <el-col :span="12" v-if="currentLog.newValues">
              <h5>变更后</h5>
              <el-input
                type="textarea"
                :rows="6"
                :value="formatJson(currentLog.newValues)"
                readonly
              />
            </el-col>
          </el-row>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Search, Refresh } from '@element-plus/icons-vue'
import { getAuditLogList, getActionTypes, getModules, type AuditLogDto, type AuditLogQueryParams } from '@/api/auditLog'

// 响应式数据
const loading = ref(false)
const logList = ref<AuditLogDto[]>([])
const totalCount = ref(0)
const actionTypes = ref<Array<{ value: string; label: string }>>([])
const modules = ref<Array<{ value: string; label: string }>>([])
const dateRange = ref<[string, string] | null>(null)

// 搜索表单
const searchForm = reactive<AuditLogQueryParams>({
  actionType: '',
  module: '',
  keyword: '',
  startTime: null,
  endTime: null,
  userId: undefined,
  result: '',
  pageDto: {
    pageNumber: 1,
    pageSize: 20
  }
})

// 分页
const pagination = reactive({
  page: 1,
  pageSize: 20
})

// 详情对话框
const detailDialogVisible = ref(false)
const currentLog = ref<AuditLogDto | null>(null)

// 计算属性
const totalPages = computed(() => Math.ceil(totalCount.value / pagination.pageSize))

// 方法
const loadLogList = async () => {
  loading.value = true
  try {

    const params: AuditLogQueryParams = {
      ...searchForm,
      pageDto: {
        pageNumber: pagination.page,
        pageSize: pagination.pageSize
      }
    }

    // 处理时间范围
    if (dateRange.value) {
      params.startTime = dateRange.value[0]
      params.endTime = dateRange.value[1]
    }

    const response = await getAuditLogList(params)
    if (response.code === 200) {
      logList.value = response.data?.items || []
      totalCount.value = response.data?.totalCount || 0
    } else {
      ElMessage.error(response.message || '加载日志列表失败')
    }
  } catch (error) {
    console.error('加载日志列表失败:', error)
    ElMessage.error('加载日志列表失败')
  } finally {
    loading.value = false
  }
}

const loadActionTypes = async () => {
  try {
    const response = await getActionTypes()
    if (response.code === 200) {
      actionTypes.value = response.data || []
    }
  } catch (error) {
    console.error('加载操作类型失败:', error)
  }
}

const loadModules = async () => {
  try {
    const response = await getModules()
    if (response.code === 200) {
      modules.value = response.data || []
    }
  } catch (error) {
    console.error('加载模块列表失败:', error)
  }
}

const handleSearch = () => {
  pagination.page = 1
  loadLogList()
}

const handleReset = () => {
  Object.assign(searchForm, {
    actionType: '',
    module: '',
    keyword: '',
    startTime: '',
    endTime: '',
    userId: undefined,
    result: '',
    pageDto: {
      pageNumber: 1,
      pageSize: 20
    }
  })
  dateRange.value = null
  pagination.page = 1
  loadLogList()
}

const handleRefresh = () => {
  loadLogList()
}

const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.page = 1
  loadLogList()
}

const handleCurrentChange = (page: number) => {
  pagination.page = page
  loadLogList()
}

const handleViewDetail = (log: AuditLogDto) => {
  currentLog.value = log
  detailDialogVisible.value = true
}

const formatDateTime = (dateTime: string) => {
  return new Date(dateTime).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

const getActionTypeTagType = (actionType: string) => {
  const typeMap: Record<string, string> = {
    '登录': 'success',
    '登出': 'info',
    '创建': 'primary',
    '更新': 'warning',
    '删除': 'danger',
    '添加': 'success',
    '修改': 'warning',
    '重置密码': 'danger',
    '上传': 'info',
    '下载': 'info'
  }
  return typeMap[actionType] || 'info'
}

const formatJson = (jsonString: string) => {
  try {
    const obj = JSON.parse(jsonString)
    return JSON.stringify(obj, null, 2)
  } catch {
    return jsonString
  }
}

// 生命周期
onMounted(() => {
  loadActionTypes()
  loadModules()
  loadLogList()
})
</script>

<style scoped>
.audit-log-container {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  color: #303133;
}

.page-header p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.search-section {
  margin-bottom: 20px;
}

.search-form {
  margin-bottom: 0;
}

.table-section {
  margin-bottom: 20px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.table-title {
  display: flex;
  align-items: center;
  gap: 12px;
}

.table-title h3 {
  margin: 0;
  color: #303133;
}

.total-count {
  color: #909399;
  font-size: 14px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.log-detail {
  max-height: 600px;
  overflow-y: auto;
}

.user-real-name {
  font-size: 12px;
  color: #909399;
}

.data-changes {
  margin-top: 20px;
}

.data-changes h4 {
  margin: 0 0 12px 0;
  color: #303133;
}

.data-changes h5 {
  margin: 0 0 8px 0;
  color: #606266;
  font-size: 14px;
}
</style>
